package com.mars.ecsheet.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mars.ecsheet.entity.WorkSheetEntity;
import com.mars.ecsheet.repository.WorkSheetRepository;
import com.mars.ecsheet.service.IHistroyService;
import com.mars.ecsheet.utils.RedisUtils;
import com.mars.ecsheet.utils.SheetUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.*;

@Slf4j
@Service
public class HistoryService implements IHistroyService {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private WorkSheetRepository workSheetRepository;


    @SneakyThrows
    @Async
    @Override
    public void process(String wbId) {
        long t1 = System.currentTimeMillis();

        long ver = redisUtils.increment("incrby_"+wbId, 1);
        redisUtils.rightPush("his_"+wbId, buildHistoryData(wbId, "", new Date(), ver));
        redisUtils.add("ver_"+wbId, buildVersionData(wbId, ver, SheetUtil.getDefaultSheetData()));

//        List<Object> list = redisUtils.range("his_"+wbId, 0, -1);
//        log.info(JSONUtil.parseArray(list).toString());

//        log.info(redisUtils.getMapString("ver_"+wbId, "1"));
//        log.info(redisUtils.getMapString("ver_"+wbId, "2"));

//        Thread.sleep(5000);
        long t2 = System.currentTimeMillis();
        log.info("task1方法耗时 {} ms" , t2-t1);
    }

    private JSONObject getSheetData(String wbId) {
        List<WorkSheetEntity> wsList = workSheetRepository.findAllBywbId(wbId);
        List<JSONObject> list = new ArrayList<>();
        wsList.forEach(ws -> {
            list.add(ws.getData());
        });
        if (!list.isEmpty()) {
            return SheetUtil.buildSheetData(list);
        }
        return SheetUtil.getDefaultAllSheetData();
    }

    private JSONObject buildHistoryData(String wbId, String username, Date updateTime, long ver) {
        JSONObject result = new JSONObject();
        result.put("username", username);
        result.put("updateTime", updateTime);
        result.put("ver", ver);
        return result;
    }

    private Map<String, Object> buildVersionData(String wbId, long ver, List<JSONObject> sheetData) {
        Map<String, Object> hashData = new HashMap<>();
        hashData.put(ver+"", sheetData);
        return hashData;
    }
}
